package com.itmuch.cloud.fitler;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class JwtAuthenticationFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();

        // 跳过登录等不需要认证的路径
        if (path.contains("/auth/login")) {
            return chain.filter(exchange);
        }

        // 从请求头获取Token
        String token = request.getHeaders().getFirst("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            // 没有Token，返回401未授权
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        // 验证Token（这里简化了，实际需要解析和校验JWT）
        if (!isValidToken(token)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        // 验证通过，将用户信息放入请求头，传递给下游服务
        ServerHttpRequest mutatedRequest = request.mutate()
                .header("X-User-Id", "12345") // 从Token中解析出的用户ID
                .build();

        return chain.filter(exchange.mutate().request(mutatedRequest).build());
    }

    private boolean isValidToken(String token) {
        // 实现你的JWT校验逻辑
        return true; // 示例
    }

    @Override
    public int getOrder() {
        // 过滤器的执行顺序，数值越小优先级越高
        return 0;
    }
}